package cn.biplam.back.operator.mdManage;

import java.util.ArrayList;

import cn.biplam.back.operator.tree.OptTreeFiniation;
import cn.biplam.common.client.DataFilter;
import cn.biplam.common.client.Operator;
import cn.biplam.common.client.OperatorResult;
import cn.biplam.common.interfaces.DataOperator;
import cn.biplam.common.opcode.mdManage.TypeCode.OptModelIndexCode;
import cn.biplam.common.struc.BaseStruc;
import cn.biplam.common.struc.BaseStruc.IndexTableStruc;
import cn.biplam.common.tools.TOOLS;
import cn.biplam.common.wrapper.ErrorMessage;

/**
 * 业务模型索引表数据操作类<br>
 * <ul>功能：
 * 	<li> 根据业务模型类型和表ID获取表索引信息
 * 	<li> 获取业务模型主题树
 * 	<li> 获取业务模型根主题下所有表
 * </ul>
 * @author XiaoRuxing 2009-7-3下午06:42:39
 * @version 1.0
 */
public class OptModelIndex extends DataOperator{
	
	/** 数据库类型表表名 */
	public static final String tName="model_index";
	
	public OptModelIndex() throws ErrorMessage {
		super(tName);
	}

	/**
	 * 实现类的交换器，根据交换代码执行相应的方法生成并执行SQL语句，返回执行结果
	 * @return 交换代码对应Sql的执行结果
	 * @throws ErrorMessage
	 */
	protected OperatorResult _exchange() throws ErrorMessage {
		ArrayList<String> sql=new ArrayList<String>();
		if(opId.equals(OptModelIndexCode.GetBy_RealId_And_ModelType)){
			this.selectByRealIdAndModelType(sql);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Get_Model_Theme_Tree)){
			this.getModelThemeTree(sql, filter);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Get_Theme_Tables)){
			this.queryThemeTables(sql, filter);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Get_Model_Root_Theme)){
			this.getRootThemeTree(sql, filter);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Query_Parent)){
			this._queryParent(sql, filter);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Query_Table_Root_Theme)){
			this._queryTableRootTheme(sql, filter);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Query_Is_Parent)){
			this.queryIsParent(sql, filter);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.GetBy_RealId_And_ModelType_And_OptType)){
			this.selectByRealIdAndModelTypeAndOptType(sql);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Query_Have_Child)){
			this._haveChild(sql);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Select_Node_Name)){
			this.getNodeNameById(sql, filter);
			return this.doing(sql,Operator_Type.Select);
		}else if(opId.equals(OptModelIndexCode.Select_Node_By_ID)){
			this.getNodeByNodeId(sql, filter);
			return this.doing(sql,Operator_Type.Select);
		}else{
			throw new ErrorMessage("Data Operator id not found:"+ opId+" !");
		}
	}
	
	/**
	 * 获取模型主题树 
	 * <ul> 需要参数有:
	 *  <li> 模型类型
	 *  <li> 向下获取的级别
	 *  <li> 节点ID
	 * </ul> 
	 * @param filter
	 * @throws ErrorMessage
	 */
	private void getModelThemeTree(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		String nodeType = filter.getValue(BaseStruc.IndexTableStruc.NODE_TYPE);
		String filterSql = " operator_type<'3' and node_type='"+nodeType+"'";
		String levelDown = filter.getValue("level_down");
		String rootValue = filter.getValue(BaseStruc.IndexTableStruc.NODE_ID);
		OptTreeFiniation tf = new OptTreeFiniation();
		tf.set(this.tableName, 
				levelDown, 
				filterSql, 
				rootValue, 
				BaseStruc.IndexTableStruc.NODE_ID, 
				BaseStruc.IndexTableStruc.NODE_PARENT,
				BaseStruc.IndexTableStruc.NODE_SEQUENCE);
		String sqlStr = tf.getSql();
		if(TOOLS.StringIsEmpty(sqlStr)){
			return;
		}
		sql.add(tf.getSql());
	}
	
	/**
	 * 获取模型主题树 
	 * <ul> 需要参数有:
	 *  <li> 模型类型
	 *  <li> 向下获取的级别
	 *  <li> 节点ID
	 * </ul> 
	 * @param filter
	 * @throws ErrorMessage
	 */
	private void getRootThemeTree(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		String nodeType = filter.getValue(BaseStruc.IndexTableStruc.NODE_TYPE);
		String filterSql = " operator_type='1' and node_type='"+nodeType+"'";
		String levelDown = filter.getValue("level_down");
		String rootValue = filter.getValue(BaseStruc.IndexTableStruc.NODE_ID);
		OptTreeFiniation tf = new OptTreeFiniation();
		tf.set(this.tableName, 
				levelDown, 
				filterSql, 
				rootValue, 
				BaseStruc.IndexTableStruc.NODE_ID, 
				BaseStruc.IndexTableStruc.NODE_PARENT,
				BaseStruc.IndexTableStruc.NODE_SEQUENCE);
		sql.add(tf.getSql());
	}
	
	/**
	 * 查询指定节点是否是另一个节点的父亲,如果是返回1、否则返回0
	 */
	private void queryIsParent(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		String parent = filter.getValue(BaseStruc.IndexTableStruc.NODE_PARENT);
		String nodeCode = filter.getValue(BaseStruc.IndexTableStruc.NODE_CODE);
		OperatorResult rs = Operator.get(OptModelIndexCode.GetBy_RealId_And_ModelType, userId, filter, dbResource);
		if(rs==null||rs.isNull()){
			throw new ErrorMessage("Node "+filter.getValue(BaseStruc.IndexTableStruc.NODE_CODE)+" can not find !");
		}
		String nodeID = rs.getValue(BaseStruc.IndexTableStruc.NODE_ID);
		String nodeType = rs.getValue(BaseStruc.IndexTableStruc.OPERATOR_TYPE);
		nodeCode = rs.getValue(BaseStruc.IndexTableStruc.NODE_CODE);
		while(!nodeType.equals("1")){
			filter.put(BaseStruc.IndexTableStruc.NODE_ID, nodeID);
			rs = Operator.get(OptModelIndexCode.Query_Parent, userId, filter, dbResource);
			if(nodeCode.equals(parent)){
				this.result.setStrResult("1");
				break;
			}
			this.result.setStrResult("0");
			if(rs!=null && !rs.isNull()){
				nodeID = rs.getValue(BaseStruc.IndexTableStruc.NODE_ID);
				nodeType = rs.getValue(BaseStruc.IndexTableStruc.OPERATOR_TYPE);
				nodeCode = rs.getValue(BaseStruc.IndexTableStruc.NODE_CODE);
			}else{
				break;
			}
		}
	}
	
	/**
	 * 查询节点(表、主题)所属的根主题
	 * @throws ErrorMessage 
	 */
	private void _queryTableRootTheme(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		OperatorResult rs = Operator.get(OptModelIndexCode.GetBy_RealId_And_ModelType, userId, filter, dbResource);
		if(rs==null||rs.isNull()){
			throw new ErrorMessage("Node "+filter.getValue(BaseStruc.IndexTableStruc.NODE_CODE)+" can not find !");
		}
		String nodeID = rs.getValue(BaseStruc.IndexTableStruc.NODE_ID);
		String nodeType = rs.getValue(BaseStruc.IndexTableStruc.OPERATOR_TYPE);
		while(!nodeType.equals("1")){
			filter.put(BaseStruc.IndexTableStruc.NODE_ID, nodeID);
			rs = Operator.get(OptModelIndexCode.Query_Parent, userId, filter, dbResource);
			if(rs!=null && !rs.isNull()){
				nodeID = rs.getValue(BaseStruc.IndexTableStruc.NODE_ID);
				nodeType = rs.getValue(BaseStruc.IndexTableStruc.OPERATOR_TYPE);
			}else{
				break;
			}
		}
		this.result.setStrResult(nodeID);
	}
	
	/**
	 * 根据节点ID查询节点的父亲节点
	 * 
	 */
	private void _queryParent(ArrayList<String> sql,DataFilter filter){
		StringBuilder sp=new StringBuilder();
		sp.append(" select t.node_id,t.node_parent,t.node_name,  ");
		sp.append("        t.node_desc,t.node_code,t.node_type,t.operator_type   ");
		sp.append("  from model_index t                          ");
		sp.append(" where t.node_id = (                          ");
		sp.append("      select a.node_parent                    ");
		sp.append("        from model_index a                    ");
		sp.append("       where a.node_id = '"+filter.getValue(BaseStruc.IndexTableStruc.NODE_ID)+"'");
		sp.append(" )                                            ");
		sql.add(sp.toString());
	}
	
	/**
	 * 获取模型主题下的所有表节点 
	 * <ul> 需要参数有:
	 *  <li> 模型类型
	 *  <li> 主题ID
	 * </ul> 
	 * @param filter
	 * @throws ErrorMessage
	 */
	private void queryThemeTables(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		String nodeType = filter.getValue(BaseStruc.IndexTableStruc.NODE_TYPE);
		String filterSql = " node_type='"+nodeType+"'"+" and operator_type='3'";
		String levelDown = "-1";
		String rootValue = filter.getValue(BaseStruc.IndexTableStruc.NODE_ID);
		OptTreeFiniation tf = new OptTreeFiniation();
		tf.set(tableName, levelDown, filterSql, rootValue,BaseStruc.IndexTableStruc.NODE_ID, BaseStruc.IndexTableStruc.NODE_PARENT, BaseStruc.IndexTableStruc.NODE_SEQUENCE);
		String sqlStr = tf.getSql();
		if(sqlStr!=null){
			sql.add(sqlStr);
		}
	}
	
	/**
	 *  根据节点物理ID和模型类型查询节点
	 * @return  
	 * @throws ErrorMessage
	 */
	public void selectByRealIdAndModelType(ArrayList<String> sql) throws ErrorMessage {
		StringBuilder sp=new StringBuilder();
		sp.append(" select t.* ");
		sp.append("  from model_index t                          ");
		sp.append(" where t.node_id = (                          ");
		sp.append("      select a.node_id                        ");
		sp.append("        from model_index a                    ");
		sp.append("       where a.node_code = '"+filter.getValue(BaseStruc.IndexTableStruc.NODE_CODE)+"'");
		sp.append("         and a.node_type = '"+filter.getValue(BaseStruc.IndexTableStruc.NODE_TYPE)+"'");
		sp.append(" )                                            ");
		sql.add(sp.toString());
	}
	
	/**
	 *  根据节点物理ID和模型类型查询节点
	 * @return  
	 * @throws ErrorMessage
	 */
	public void selectByRealIdAndModelTypeAndOptType(ArrayList<String> sql) throws ErrorMessage {
		StringBuilder sp=new StringBuilder();
		sp.append(" select * ");
		sp.append("  from model_index t                          ");
		sp.append(" where t.node_code = '"+filter.getValue(BaseStruc.IndexTableStruc.NODE_CODE)+"'");
		sp.append("   and t.node_type = '"+filter.getValue(BaseStruc.IndexTableStruc.NODE_TYPE)+"'");
		sp.append("   and t.operator_type = '"+filter.getValue(BaseStruc.IndexTableStruc.OPERATOR_TYPE)+"'");
		sql.add(sp.toString());
	}
	
	/**
	 *  根据节点物理ID和模型类型查询节点
	 * @return  
	 * @throws ErrorMessage
	 */
	public void _haveChild(ArrayList<String> sql) throws ErrorMessage {
		StringBuilder sp=new StringBuilder();
		sp.append("Select * from model_index where node_parent =(");
		sp.append(" select t.node_id  ");
		sp.append("  from model_index t                          ");
		sp.append(" where t.node_code = '"+filter.getValue(BaseStruc.IndexTableStruc.NODE_CODE)+"'");
		sp.append("   and t.node_type = '"+filter.getValue(BaseStruc.IndexTableStruc.NODE_TYPE)+"'");
		sp.append("   and t.operator_type = '"+filter.getValue(BaseStruc.IndexTableStruc.OPERATOR_TYPE)+"'");
		sp.append(")");
		sql.add(sp.toString());
	}
	
	/**
	 * 根据节点ID获取节点信息(树回调索引表节点名称用)
	 * @throws ErrorMessage 
	 */
	private void getNodeNameById(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		StringBuilder sp=new StringBuilder();
		sp.append(" select node_id,node_name from "+this.tableName);
		sp.append(" where "+IndexTableStruc.NODE_CODE+"='"+filter.getValue()+"'");
		sql.add(sp.toString());
	}
	
	/**
	 * 根据节点ID获取节点信息(树回调索引表节点名称用)
	 * @throws ErrorMessage 
	 */
	private void getNodeByNodeId(ArrayList<String> sql,DataFilter filter) throws ErrorMessage{
		StringBuilder sp=new StringBuilder();
		sp.append(" select * from "+this.tableName);
		sp.append(" where "+IndexTableStruc.NODE_ID+"='"+filter.getValue(BaseStruc.IndexTableStruc.NODE_ID)+"'");
		sql.add(sp.toString());
	}

}
